<template>
  <el-card shadow="always" :body-style="{ padding: '20px' }">
    <el-input disabled :value="$route.query.roleName"></el-input>
    <el-tree
      :data="RolePermissionList"
      ref="treeRef"
      show-checkbox
      node-key="id"
      default-expand-all
      :props="defaultProps"
    >
    </el-tree>
    <el-button type="primary" @click="save">保存</el-button>
    <el-button @click="cancel">取消</el-button>
  </el-card>
</template>

<script>
import { reqGetRolePermissionList, reqAssignRoleApi } from "@/api/acl/role";
export default {
  name: "roleAuth",
  data() {
    return {
      defaultProps: {
        children: "children",
        label: "name",
      },
      RolePermissionList: [],
      roleIds: [],
      initArr: [],
      treeRef: "",
    };
  },
  methods: {
    // 获取所有选中的id
    getCheckedIds(auths) {
      auths.forEach((item) => {
        if (item.select && item.level === 4) {
          this.initArr.push(item.id);
        } else if (item.children.length) {
          this.getCheckedIds(item.children);
        }
      });
      return this.initArr;
    },
    // 获取角色权限列表
    async getRolePermissionList() {
      const roleId = this.$route.query.id;
      const RolePermissionList = await reqGetRolePermissionList(roleId);
      // console.log(RolePermissionList);
      this.RolePermissionList = RolePermissionList.data.children;
      this.getCheckedIds(this.RolePermissionList);
      const checkedIds = this.getCheckedIds(this.RolePermissionList);
      // console.log(checkedIds);
      this.$refs.treeRef.setCheckedKeys(checkedIds);
      // console.log(this.$refs)
    },
    // 分配权限点击保存的回调
    save() {
      // 得到所有全选的id  getCheckedKeys方法
      const checkedIds = this.$refs.treeRef.getCheckedKeys();
      // 得到所有半选的id  getHalfCheckedKeys方法
      const halfCheckedIds = this.$refs.treeRef.getHalfCheckedKeys();
      // 合并全选和半选的id， 并用逗号连接成串
      var ids = checkedIds.concat(halfCheckedIds).join(",");
      reqAssignRoleApi(this.$route.query.id, ids).then(() => {
        this.$message.success("分配权限成功");

        // this.getRolePermissionList();
        // 跳转到角色列表页面
        this.$router.replace("/acl/role");
      });
    },
    // 分配权限点击取消的回调
    cancel() {
      this.$message.warning("您已取消分配权限");
      this.$router.replace("/acl/role");
    },
  },
  mounted() {
    this.getRolePermissionList();
  },
};
</script>

<style scoped></style>
